package com.acane.instagram.feature.search

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.wear.compose.material3.IconButton
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.design.theme.Spacer
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchDetailRoute(
    navController: NavController,
    toProfile: (String) -> Unit,
    toPost: (String, Int) -> Unit,
    toDetail: (String) -> Unit
) {
    SearchDetailScreen(
        navController = navController,
        toProfile = toProfile,
        toPost = toPost,
        toDetail = toDetail,
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchDetailScreen(
    navController: NavController,
    toProfile: (String) -> Unit,
    searchViewModel: SearchViewModel = viewModel(),
    toPost: (String, Int) -> Unit,
    toDetail: (String) -> Unit,
) {
    val keyboardController = LocalSoftwareKeyboardController.current // 新增

    var searchText by remember { mutableStateOf("") }
    // 新增焦点控制
    val focusRequester = remember { FocusRequester() }
    var hasFocus by remember { mutableStateOf(false) }


    val loading by searchViewModel.loading.collectAsState() // 收集加载状态
    // 管理HorizontalPager的当前页码
    val pagerState = rememberPagerState(initialPage = 0) { 2 } // 强制设置初始页为0

    // 焦点变化监听（优化版）
    LaunchedEffect(hasFocus) {
        if (hasFocus) {
            Log.d("Focus", "获得焦点，切换到第0页")
            pagerState.animateScrollToPage(0)
        }
    }
    // 自动请求焦点（新增）
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }

    // 监听搜索数据
    val userSearchResultData = searchViewModel.userSearchResults.collectAsState()
    val postSearchResultData = searchViewModel.postSearchResults.collectAsState()


    val scope: CoroutineScope = rememberCoroutineScope()
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    // 空标题
                },
                navigationIcon = {
                    IconButton(
                        onClick = { navController.popBackStack() },
                        modifier = Modifier
                    ) {
                        Image(
                            painter = painterResource(R.drawable.arrow_left),
                            contentDescription = "返回",
                            modifier = Modifier
                                .size(32.dp) // 增大图标尺寸
                                .padding(4.dp), // 增加内边距防止被覆盖
                            colorFilter = ColorFilter.tint(Color.Black) // 强制设置图标颜色
                        )
                    }
                },
                actions = {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(start = 56.dp) // 左侧留出返回按钮空间
                            .height(55.dp), // 增加高度确保文字可见
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        TextField(
                            value = searchText,
                            onValueChange = { newText ->
                                searchText = newText
                                searchViewModel.search(newText)
                                scope.launch {
                                    keyboardController?.show() // 输入时保持键盘可见
                                    pagerState.scrollToPage(0) // 强制回到第一页
                                }
                            },
                            keyboardOptions = KeyboardOptions.Default.copy(
                                imeAction = androidx.compose.ui.text.input.ImeAction.Done
                            ),
                            keyboardActions = KeyboardActions(
                                onDone = {
                                    scope.launch {
                                        keyboardController?.hide() // 先隐藏键盘
                                        Log.d("Search", "切换到第1页")
                                        pagerState.animateScrollToPage(1) // 再切换页面
                                    }
                                }
                            ),
                            placeholder = {
                                Row(
                                    modifier = Modifier.fillMaxSize(),
                                    verticalAlignment = Alignment.CenterVertically,
                                ) {
                                    Image(
                                        painter = painterResource(id = R.drawable.search),
                                        contentDescription = null,
                                        modifier = Modifier
                                            .size(15.dp),
                                        contentScale = ContentScale.Crop
                                    )
                                    Text(
                                        text = "搜索",
                                        fontSize = 12.sp,
                                    )
                                }
                            },
                            shape = RoundedCornerShape(5.dp),
                            modifier = Modifier
                                .fillMaxWidth()
                                .onFocusChanged { state ->
                                    hasFocus = state.isFocused // 监听焦点变化
                                }
                                .focusRequester(focusRequester),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = InstagramLightGray,
                                unfocusedContainerColor = InstagramLightGray,
                                focusedIndicatorColor = Color.Transparent,
                                unfocusedIndicatorColor = Color.Transparent,
                                focusedTextColor = Color.Black,
                                unfocusedTextColor = Color.Black
                            ),
                            singleLine = true
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White
                ),
            )
        },
        containerColor = Color.White
    ) { padding ->
        // 显示加载状态
        if (loading) {
            Box() {
                CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
            }
        } else {
            HorizontalPager(
                state = pagerState,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding),
                userScrollEnabled = false
            ) { page ->
                when (page) {
                    // 第一页：用户搜索结果
                    0 -> UserSearchResultPage(
                        userSearchResultData = userSearchResultData.value ?: emptyList(),
                        toProfile = toProfile,
                    )

                    // 第二页：帖子搜索结果
                    1 -> SearchResultPage(
                        userSearchResultData = userSearchResultData.value ?: emptyList(),
                        postSearchResultData = postSearchResultData.value ?: emptyList(),
                        scope = scope,
                        toProfile = toProfile,
                        searchViewModel = searchViewModel,
                        navController = navController,
                        toPost = toPost,
                        toDetail = toDetail,
                    )
                }
            }
        }
    }
}

@Composable
fun UserSearchResultPage(
    userSearchResultData: List<UserInfo>,
    toProfile: (String) -> Unit,
) {
    // 搜索结果列表,搜索阶段只显示用户搜索列表
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
    ) {
        items(userSearchResultData) { userData ->
            // 搜索结果预览
            Row(
                modifier = Modifier
                    .clickableNoRipple {
                        userData.id?.let { toProfile(it) }
                    }
                    .padding(10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 头像
                AsyncImage(
                    model = userData.avatar?.let {
                        val url = "${Config.ADDRESS}avatars/$it"
                        Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                        url
                    },
                    contentScale = ContentScale.Crop,
                    contentDescription = "当前用户头像",
                    modifier = Modifier
                        .size(50.dp)
                        .clip(shape = CircleShape),
                    error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                )
                // 添加间隔
                Spacer()
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                ) {
                    userData.userName?.let {
                        Text(
                            text = it,
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color.Black
                        )
                    }
                    Text(
                        text = userData.nickName ?: "",
                        fontSize = 14.sp,
                        color = InstagramDarkGray
                    )
                }
            }
        }
    }
}
@Composable
fun SearchResultPage(
    userSearchResultData: List<UserInfo>,
    postSearchResultData: List<PostInfo>,
    scope: CoroutineScope,
    toProfile: (String) -> Unit,
    navController: NavController,
    searchViewModel: SearchViewModel,
    toPost: (String, Int) -> Unit,
    toDetail: (String) -> Unit,
) {
    val imageList: List<String> = postSearchResultData.map { it.thumbnailUrl }


    val titles: List<String> = listOf(
        "帖子", "帐户"
    )

    // TabRow 和 Pager
    val pagerState = com.google.accompanist.pager.rememberPagerState(initialPage = 0)

    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        TabRow(
            selectedTabIndex = pagerState.currentPage,
            containerColor = Color.White,
            tabs = {
                titles.forEachIndexed { index, title ->
                    Tab(
                        modifier = Modifier.padding(10.dp),
                        selected = pagerState.currentPage == index,
                        onClick = {
                            scope.launch {
                                pagerState.animateScrollToPage(index)
                            }
                        },
                    ) {
                        Text(
                            text = title,
                            fontSize = 14.sp,
                        )
                    }
                }
            }
        )

        // Pager
        com.google.accompanist.pager.HorizontalPager(
            count = titles.size,
            state = pagerState,
            modifier = Modifier
                .weight(1f)
        ) { page ->
            when (page) {
                0 -> if (postSearchResultData.isEmpty()) {
                    Text(
                        text = "暂无内容", modifier = Modifier.align(Alignment.CenterHorizontally)
                    )
                } else {
                    CustomImageLayout(
                        postSearchResultData =postSearchResultData,
                        searchViewModel = searchViewModel,
                        toPost = toPost,
                        toDetail = toDetail,
                    )
                }

                1 -> if (userSearchResultData.isEmpty()) {
                    Text(
                        text = "暂无内容", modifier = Modifier.align(Alignment.CenterHorizontally)
                    )
                } else {
                    UserSearchResultPage(
                        userSearchResultData = userSearchResultData,
                        toProfile = toProfile,
                    )

                }
            }
        }
    }

}
@Preview
@Composable
fun PreviewSearchDetailScreen() {
//    SearchDetailScreen(
//        navController =
//    )
}